﻿using System;
using System.Collections.Generic;
using Assets.Scripts.Net;
using Assets.Scripts.Net.Data;
using Assets.Scripts.Net.Data.Model;
using Assets.Scripts.UI.Item;
using UnityEngine;
using UnityEngine.UI;

namespace Assets.Scripts.UI.Panel
{
    //错题本的Panel
    public class CollectPanel:UIBase<CollectPanel>
    {
        public Button ExitButton;
        public Button ClearButton;
        public Button ExerciseButton;
        public Button SettingButton;
        public Transform Content_Course;
        public Transform Content_Exercise;
        public Transform Viewport_Warp;
        public Toggle AutoRemoveToggle;
        private UIWarpContent warpContent;  
        public static CourseItem NowClickItem { get; set;}//记录当前点击的courseItem
        public List<QueInfo> NowCourseQueInfos { get; set; }//当前选择课程的问题信息
        public List<QueInfo> QueInfos { get; set; } //总的题目集合
        protected override UIType UIType
        {
            get { return UIType.Panel;}
        }

        public static CollectPanel _Instance;

        protected override void InitOnDestroy()
        {
            _Instance = null;
        }

        protected override void InitOnAwake()
        {
            _Instance = this;
            AutoFindComponent(transform, true);
            ExitButton.onClick.AddListener(Exit); 
            ClearButton.onClick.AddListener(OnClearButtonClick);
            ExerciseButton.onClick.AddListener(OnExerciseButtonClick);
            SettingButton.onClick.AddListener(() => { CreatePanel(PanelType.SettingPanel); });
            AutoRemoveToggle.onValueChanged.AddListener(x =>
            {
                PlayerPrefs.SetInt("AutoRemoveRightQuestions", x ? 1 : 0);
            });
            int index= PlayerPrefs.GetInt("AutoRemoveRightQuestions");
            AutoRemoveToggle.isOn = Convert.ToBoolean(index);
            warpContent = Viewport_Warp.GetComponent<UIWarpContent>();
            warpContent.onInitializeItem = OnInitializeItem;
        }

        /// <summary>
        /// 清理
        /// </summary>
        private void OnClearButtonClick()
        {
            if (NowClickItem == null)
            {
                UIManager._Instance.ShowTipInfo("当前未选择课程");
            }
            else
            {
                Dictionary<string, object> dict = NetManager.Instance.GetDict();
                string ids = "";           
                if (NowCourseQueInfos == null)
                {
                    UIManager._Instance.ShowTipInfo("该课程下没有错题数据");
                    return;
                }
                TipPanel panel = CreatePanel(PanelType.TipPanel).GetComponent<TipPanel>();
                panel.Init("确定清空课程下的所有题目吗？", () =>
                {
                    for (int i = 0; i < NowCourseQueInfos.Count; i++)
                    {
                        ids += ";" + NowCourseQueInfos[i].id;
                    }
                    dict.Add("id", ids);
                    NetManager.Instance.SendRequest(RequestType.ClearErrorList, dict, () =>
                    {
                        warpContent.Clear();
                        DeleteQueInfoByIds(ids);
                    });
                });     
            }                 
        }


        /// <summary>
        /// 删除问题的数据
        /// </summary>
        /// <param name="ids"></param>
        private void DeleteQueInfoByIds(string ids)
        {
            string[] str = ids.Split(';');
            List<QueInfo>needRemoveQueInfos=new List<QueInfo>();
            for (int i = 0; i < str.Length; i++)
            {
                if (!string.IsNullOrEmpty(str[i]))
                {
                    for (int j = 0; j < QueInfos.Count; j++)
                    {
                        if (str[i] == QueInfos[j].id.ToString())
                        {
                            needRemoveQueInfos.Add(QueInfos[j]);                      
                        }
                    }   
                }                             
            }
            for (int i = 0; i < needRemoveQueInfos.Count; i++)
            {
                QueInfos.Remove(needRemoveQueInfos[i]);
                NowCourseQueInfos.Remove(needRemoveQueInfos[i]);
            }
        }

        /// <summary>
        /// 练习
        /// </summary>
        private void OnExerciseButtonClick()
        {
            List<QueInfo> queInfos = NowCourseQueInfos;              
            List<AnsInfo> ansInfos =
                NetReaderFactory.Instance().GetInfoByType<List<AnsInfo>>() as List<AnsInfo>;
            List<QueInfo> questions = new List<QueInfo>();
            if (queInfos == null || ansInfos == null||NowClickItem==null||queInfos.Count==0)
            {
                UIManager._Instance.ShowTipInfo("当前没有习题数据，不能练习");
                return;
            }
            for (int i = 0; i < queInfos.Count; i++)
            {
                if (queInfos[i].courseid == NowClickItem.CourseId)
                {
                    questions.Add(queInfos[i]);
                }
            }
            //给题目添加分数
            int count = queInfos.Count;
            if (count <= 0)
                return;
            int score = 100/count;
            for (int i = 0; i < queInfos.Count; i++)
            {
                queInfos[i].score = score;
            }
            ExamPanel panel= CreatePanel(PanelType.ExamPanel).GetComponent<ExamPanel>();
            panel.Init(ExamType.WrongExercise, NowClickItem.CourseNameText.text+"【习题练习】", 0, questions,ansInfos,0);
        }

        /// <summary>
        /// 初始化方法
        /// </summary>  
        public void Init(List<CourseInfo>infos,List<QueInfo>queInfos)//课程信息。。。。
        {
            QueInfos = queInfos;
            for (int i = 0; i < infos.Count; i++)
            {
                Transform tsf = CreateItem(ItemType.CourseItem);
                tsf.SetParent(Content_Course);
                tsf.localScale = Vector3.one;
                tsf.localPosition = Vector3.zero;
                CourseItem item= tsf.GetComponent<CourseItem>();
                item.Init(infos[i], NetConstValue.Collect_CourseInfo, new[] {Content_Exercise});
                if (i == 0)
                {
                    item.CourseButton.onClick.Invoke();
                }
            }
        }

        public void OnCourseButtonClick(int courseId)
        {
            NowCourseQueInfos=new List<QueInfo>();
            for (int i = 0; i < QueInfos.Count; i++)
            {
                if (QueInfos[i].courseid == courseId)
                {
                    NowCourseQueInfos.Add(QueInfos[i]);
                }
            }
            warpContent.Clear();
            warpContent.Init(NowCourseQueInfos.Count);
        }

        private void OnInitializeItem(GameObject go, int dataIndex)
        {
            ExerciseItem item = go.GetComponent<ExerciseItem>();
            item.Init(NowCourseQueInfos[dataIndex],dataIndex+1);
        }

        /// <summary>
        /// 删除item
        /// </summary>
        /// <param name="dataIndex"></param>
        public void DelItem(int dataIndex,int queid)
        {
            NowCourseQueInfos.RemoveAt(dataIndex);
            warpContent.DelItem(dataIndex);
            DeleteQueInfoByIds(queid.ToString());
        }

        /// <summary>
        /// 作业做完后的回调函数
        /// </summary>
        /// <param name="ids"></param>
        public void OnExercise(string ids)
        {
            string[] queIds = ids.Split(';');             
            for (int i = 0; i < queIds.Length; i++)
            {
                int id = Convert.ToInt32(queIds[i]);
                for (int j = 0; j < NowCourseQueInfos.Count; j++)
                {
                    if (NowCourseQueInfos[j].id == id)
                    {
                        NowCourseQueInfos.Remove(NowCourseQueInfos[j]);
                    }
                }
            }
            warpContent.Clear();
            warpContent.Init(NowCourseQueInfos.Count);
        }
    }
}